package com.cuiweiyou.happypaint.util;

import android.content.Context;
import android.content.res.AssetManager;
import android.graphics.Bitmap;
import android.util.Log;

import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

/**
 * www.gaohaiyan.com
 */
public class FileUtil {

    private FileUtil() {
    }

    /**
     * 创建目录
     *
     * @param dir
     * @return
     */
    public static File createDirIfNotExist(String dir) {
        File fileDir = new File(dir);
        try {
            if (!fileDir.exists()) {
                fileDir.mkdirs();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return fileDir;
    }

    /**
     * 创建文件(存在则覆盖)
     */
    public static File createOverrideFile(String path) {
        File file = new File(path);
        if (file.exists()) {
            file.delete();
        }

        try {
            file.createNewFile();
        } catch (Exception e) {
            e.printStackTrace();
        }

        return file;
    }


    /**
     * 从 assets 中复制文件到目标目录
     *
     * @param context
     * @param srcFileNames assets中的文件名
     * @param targetPath   目标目录，结尾是/
     */
    public static boolean copyAssetsFileToPath(Context context, List<String> srcFileNames, String targetPath) {
        createDirIfNotExist(targetPath);

        try {
            AssetManager assets = context.getAssets();
            String fileNames[] = assets.list("");// 获取assets目录下的所有文件及目录名
            for (String fileName : fileNames) {
                if (srcFileNames.contains(fileName)) {
                    File targetFile = new File(targetPath + fileName);
                    if (targetFile.exists()) {
                        continue;
                    }

                    InputStream is = context.getAssets().open(fileName);
                    FileOutputStream fos = new FileOutputStream(targetFile);
                    byte[] buffer = new byte[1024];
                    int byteCount = 0;
                    while ((byteCount = is.read(buffer)) != -1) {// 循环从输入流读取
                        fos.write(buffer, 0, byteCount);// 将读取的输入流写入到输出流
                    }
                    fos.flush();// 刷新缓冲区
                    is.close();
                    fos.close();
                }
            }

            return true;
        } catch (Exception e) {
            e.printStackTrace();
        }

        return false;
    }

    public static void saveImage(Bitmap bmp, String path) {
        File file = new File(path);
        BufferedOutputStream bos = null;
        try {
            if (!file.exists()) {
                file.createNewFile();
            }
            bos = new BufferedOutputStream(new FileOutputStream(file));
            bmp.compress(Bitmap.CompressFormat.PNG, 90, bos);
            bos.flush();
            bos.close();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (null != bos) {
                try {
                    bos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    public static void saveText(File f, String text) {
        PrintWriter pw = null;
        try {
            if (!f.exists()) {
                f.createNewFile();
            }

            pw = new PrintWriter(new BufferedWriter(new FileWriter(f)));
            pw.println(text);
            pw.println();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (null != pw) {
                pw.close();
            }
        }
    }

    public static void removePic(File dir, String timestemp) {
        File[] files = dir.listFiles();
        for (File file : files) {
            String name = file.getName();
            if (name.startsWith(timestemp)) {
                file.delete();
            }
        }
    }

    public static List<Map<String, String>> getAllHappyJsons(File f) {
        Map<String, Map<String, String>> map = new HashMap<>();

        File[] files = f.listFiles();
        for (File file : files) {
            String name = file.getName();
            String timestemp = name //
                    .replace("=HAPPY_JSON.txt", "") //
                    .replace("=HAPPY_PIC.png", "");
            Map<String, String> bean = map.get(timestemp);

            if (null == bean) {
                bean = new HashMap<>();
                bean.put("timestemp", timestemp);

                map.put(timestemp, bean);
            }

            if (name.contains("HAPPY_JSON")) { // json文本
                String json = readTextFile(file);
                bean.put("json", json);
            }
            if (name.contains("HAPPY_PIC")) {  // 图片
                bean.put("png", file.getAbsolutePath());
            }
        }

        return sortFile(map);
    }

    private static String readTextFile(File file) {
        FileReader fr = null;
        BufferedReader br = null;
        StringBuilder sb = new StringBuilder();
        try {
            fr = new FileReader(file);
            br = new BufferedReader(fr);
            String line;
            while ((line = br.readLine()) != null) {
                sb.append(line);
            }
        } catch (Exception e) {
            System.err.println(e.getMessage());
        } finally {
            if (null != br) {
                try {
                    br.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (null != fr) {
                try {
                    fr.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

        return sb.toString();
    }

    private static List<Map<String, String>> sortFile(Map<String, Map<String, String>> map) {
        List<Map<String, String>> list = new ArrayList<>();

        Iterator<String> iterator = map.keySet().iterator();
        while (iterator.hasNext()) {
            String timestemp = iterator.next();
            Map<String, String> m = map.get(timestemp);
            list.add(m);
        }

        if (list.size() < 2) {
            return list;
        }

        Collections.sort(list, new Comparator<Map<String, String>>() {
            @Override
            public int compare(Map<String, String> o1, Map<String, String> o2) {
                String s1 = o1.get("timestemp");
                String s2 = o2.get("timestemp");
                Log.e("ard", s1);
                try {
                    long i1 = DateFormatUtil.yyyyMMddHHmmss2millis(s1);
                    long i2 = DateFormatUtil.yyyyMMddHHmmss2millis(s2);
                    return (int) (i2 - i1); // 时间新的在前
                } catch (Exception e) {
                    return 0;
                }
            }
        });

        return list;
    }
}